package leetCode.sample;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class LengthOfLongestSubstringTest {


    @Test
    public void test() {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
        System.out.println(lengthOfLongestSubstring("bbbbb"));
        System.out.println(lengthOfLongestSubstring("pwwkew"));
        System.out.println(lengthOfLongestSubstring("dvdf"));
    }

    public int lengthOfLongestSubstring(String s) {
        if (s == null) {
            return 0;
        }
        int max = 1;
        int j = 1;
        char[] chars = s.toCharArray();
        if (chars.length == 0) {
            return 0;
        }
        Map<Character, Integer> characterMap = new HashMap<>();
        characterMap.put(chars[0], 0);
        int i = 0;
        while (i < chars.length) {
            while (j < chars.length && !characterMap.containsKey(chars[j])) {
                if (j - i + 1 > max) {
                    max = j - i + 1;
                }
                characterMap.put(chars[j], j);
                j++;
            }
            if (j == chars.length) {
                break;
            }
            if (j < chars.length) {
                int tempI = i;
                int index = characterMap.get(chars[j]);
                while (tempI <= index) {
                    characterMap.remove(chars[tempI]);
                    tempI++;
                }
                i = index + 1;
            }
        }
        return max;
    }

    public int lengthOfLongestSubstring2(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }
}
